﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using Runda.CMS.Bll;
using Runda.CMS.Common.Entity;
using Runda.CMS.Common.Utility;
using System.Collections.Generic;

namespace Runda.CMS.Portal.SalesManage
{
    public partial class SaleInvImport : BasePage
    {
        public string BillYear
        {
            get
            {
                if (Request.QueryString["billYear"] != null) return Request.QueryString["billYear"].ToString();
                else return "0000";
            }

        }

        public string BillMonth
        {
            get
            {
                if (Request.QueryString["billMonth"] != null) return Request.QueryString["billMonth"].ToString();
                else return "00";
            }

        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                DataTable dt = new BudgetBll().Companylist(base.CurrentUserID.ToString());
                ddlCompany.DataSource = dt;
                ddlCompany.DataTextField = "Departmentname";
                ddlCompany.DataValueField = "Departmentname";
                ddlCompany.DataBind();

                BudgetBll bll = new BudgetBll();
                string UnlockYearmonth = bll.GetunLockMonth(ddlCompany.SelectedValue);
                ddlBudgetMonth.SelectedValue = UnlockYearmonth.Substring(5, 2);


                if (ddlCompany.SelectedValue.Contains("润达") || ddlCompany.SelectedValue.Contains("康祥"))
                {
                    btnUFImport.Enabled = true;
                    btnExcel.Enabled = false;
                }
                else
                {
                    btnUFImport.Enabled = false;
                    btnExcel.Enabled = true;
                }
            }

        }
        protected void lnkbtnSaveAndClose_Click(object sender, EventArgs e)
        {
            string company, sYear, sMonth;
            company = ddlCompany.SelectedValue.ToString();
            sYear = ddlBudgetYear.SelectedValue.ToString();
            sMonth = ddlBudgetMonth.SelectedValue.ToString();

            int sucNum = 0;

            if (company == "")
            {
                ClientScript.RegisterStartupScript(this.GetType(), "saveandssscloseerror", "alert('请选择开票公司!');", true);
                return;
            }

            BudgetBll bll1 = new BudgetBll();
            if (bll1.BillDataStatus(sYear, sMonth, company) == 1)
            {
                ClientScript.RegisterStartupScript(this.GetType(), "saveandssscloseerror", "alert('选择月份的销售数据（导入）已关账!');", true);
                return;
            }

            if (bll1.PreBillDataStatus(sYear, sMonth, company) == 1)
            {
                ClientScript.RegisterStartupScript(this.GetType(), "saveandssscloseerror", "alert('当前月份之前的销售数据导入未完成，无法导入当前月份数据!');", true);
                return;
            }

            if (fileupload.HasFile) {
                string isXls = System.IO.Path.GetExtension(fileupload.FileName).ToString().ToLower();
                if (isXls != ".xls" && isXls != ".xlsx")
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "saveandssscloseerror", "alert('导入文件格式必须是Excel');", true);
                    return; 
                }
                string fileName = fileupload.FileName;
                fileupload.PostedFile.SaveAs(Server.MapPath("\\Temp") + "\\" + fileName);
                string filepath = Server.MapPath("\\Temp") + "\\" + fileName;

                SystemBll delbll = new SystemBll();
                new SystemBll().Delete<BGSalesBillsEntity>(" and SourceType = 2 and billUnit = BudgetUnit and cBVCode not in (select cBVCode from vw_Salebills_Zk where iNatSum_adjust <> 0) and datepart(year,dDate)  = " + BillYear + " and datepart(month,[dDate])  = " + BillMonth + " and billunit='" + company + "'");

                try
                {
                    DataTable dt = ExcelImport.ExcelToDT(filepath, "sheet1");

                    for (int index = 0; index < dt.Rows.Count; index++) {

                        string UFAccountNo = "000";
                        string BillUnit = "";
                        string Billcompany = dt.Rows[index]["开票公司"].ToString();
                        string companyNo="";
                        

                        string dDate = dt.Rows[index]["开票日期"].ToString().Trim();
                        string cBVCode = dt.Rows[index]["发票编号"].ToString().Trim();
                        string cCusCode = dt.Rows[index]["客户编号"].ToString().Trim();
                        string cCusName = dt.Rows[index]["客户名称"].ToString().Trim();
                        string cMemo = dt.Rows[index]["发票摘要"].ToString().Trim();
                        string cCategoryCode = dt.Rows[index]["大类编号"].ToString().Trim();
                        string cInvCode = dt.Rows[index]["存货编号"].ToString().Trim();
                        string cInvName = dt.Rows[index]["名称"].ToString().Trim();
                        string cInvStd = dt.Rows[index]["规格"].ToString().Trim();
                        string Quantity = dt.Rows[index]["数量"].ToString().Trim();
                        string Unit = dt.Rows[index]["含税单价"].ToString().Trim();
                        string Price = dt.Rows[index]["金额"].ToString().Trim();
                        string NatSum = dt.Rows[index]["价税合计"].ToString().Trim();


                        if (!string.Equals(company,Billcompany))
                        {
                            txtResult.Text += "开票单位（" + Billcompany + ")与当前选择的公司不符," + "导入被忽略(出错行：" + (index + 2).ToString() + ")\r\n";
                            continue;
                        }

                        switch (Billcompany)
                        {
                            case "润达":
                                companyNo = "001";
                                break;
                            case "康祥":
                                companyNo = "002";
                                break;
                            case "益信":
                                companyNo = "003";
                                break;
                            case "惠中":
                                companyNo = "004";
                                break;
                            case "华臣":
                                companyNo = "005";
                                break;
                        }

                        DateTime dtDate = DateTime.Parse(dDate);
                        int year = dtDate.Year;
                        int month = dtDate.Month;

                        if (year != Convert.ToInt32(BillYear) || month != Convert.ToInt32(BillMonth))
                        {
                            txtResult.Text += "销售发票年月（"+dDate+")与当前年月不符,"+"导入被忽略(出错行：" + (index + 2).ToString() + ")\r\n";
                            continue;
                        }


                        using (System.Transactions.TransactionScope trans = new System.Transactions.TransactionScope())
                        {
                            try
                            {
                                SystemBll bll = new SystemBll();

                                BGSalesBillsEntity entity = new BGSalesBillsEntity();
                                //entity.RegisterID = Guid.NewGuid();
                                List<CtrtCustomerEntity> customers = bll.GetAll<CtrtCustomerEntity>(" and CustomerCode = '" + cCusCode.Trim() + "' and company='" + Billcompany + "'");
                                if (customers == null || customers.Count == 0)
                                {
                                    CtrtCustomerEntity entityCust = new CtrtCustomerEntity();
                                    entityCust.CustomerID = Guid.NewGuid();
                                    entityCust.CustomerCode = cCusCode;
                                    entityCust.CustomerName = cCusName;
                                    entityCust.Company = Billcompany;
                                    entityCust.CreatedOn = DateTime.Now;
                                    entityCust.CreatorName = base.CurrentUserEntity.UserName;
                                    bll.Insert(entityCust);
                                    
                                }
                                CtrtInstrumentEntity entityInstrument = new CtrtInstrumentEntity();
                            
                                List<CtrtInstrumentEntity> instruments = bll.GetAll<CtrtInstrumentEntity>(" and instrumentCode = '" + cInvCode.Trim() + "'");
                                if (instruments != null && instruments.Count > 0)
                                {
                                    entity.cInvCode = instruments[0].instrumentCode;
                                }
                                else {

                                    entityInstrument.instrumentGUID = Guid.NewGuid();
                                    entityInstrument.instrumentCode = cInvCode;
                                    entityInstrument.instrumentName = cInvName;
                                    entityInstrument.instrumentStandard = cInvStd;
                                    entityInstrument.CategoryCode = cCategoryCode;
                                    bll.Insert(entityInstrument);
                                }

                                //更新集团的存货信息表
                                BGInstrumentEntity entityInstrumentEx =  new BGInstrumentEntity();
                                List<BGInstrumentEntity> instruentsEx = bll.GetAll<BGInstrumentEntity>(" and instrumentCode = '" + cInvCode.Trim() + "' and CompanyName='"+Billcompany+"'");

                                if (instruentsEx != null && instruentsEx.Count == 0)
                                {
                                    entityInstrumentEx.instrumentID = Guid.NewGuid();
                                    entityInstrumentEx.CompanyNo = companyNo;
                                    entityInstrumentEx.CompanyName = Billcompany;
                                    entityInstrumentEx.InstrumentCode = cInvCode;
                                    entityInstrumentEx.InstrumentName = cInvName;
                                    entityInstrumentEx.InstrumentStd = cInvStd;
                                    entityInstrumentEx.CategoryCode = cCategoryCode;

                                    List<BGInstrumentEntity> instruentstmp = bll.GetAll<BGInstrumentEntity>(" and StandardinstrumentName = '" + cInvName + "' and StandardInstrumentStd = '" + cInvStd + "'");

                                    if (instruentstmp != null && instruentstmp.Count == 1)
                                    {
                                        entityInstrumentEx.StandardInstrumentCode = instruentstmp[0].InstrumentCode;
                                        entityInstrumentEx.StandardInstrumentName = cInvName;
                                        entityInstrumentEx.StandardInstrumentStd = cInvStd;
                                    }
                                    else if (instruentstmp != null && instruentstmp.Count == 0)
                                    {
                                        entityInstrumentEx.StandardInstrumentCode = cInvCode;
                                        entityInstrumentEx.StandardInstrumentName = cInvName;
                                        entityInstrumentEx.StandardInstrumentStd = cInvStd;
                                    }

                                    entityInstrumentEx.CheckStatus = "0";
                                    entityInstrumentEx.updatetime = System.DateTime.Today;
                                    entityInstrumentEx.Updatedman = CurrentUserEntity.UserName;

                                    bll.Insert(entityInstrumentEx);
                                }

                                List<BGSalesBillsEntity> existEntity = bll.GetAll<BGSalesBillsEntity>(" and cBVCode in (select cBVCode from vw_Salebills_Zk where iNatSum_adjust <> 0) and cBVCode = '" + cBVCode.Trim() + "'");
                                if (existEntity != null && existEntity.Count > 0)
                                {
                                    txtResult.Text += "发票编号【" + cBVCode + "】已分摊,导入被忽略(出错行：" + (index + 2).ToString() + ")\r\n";
                                    continue;
                                }

                                List<BGSalesBillsEntity> existEntity1 = bll.GetAll<BGSalesBillsEntity>(" and billUnit <> BudgetUnit and cBVCode = '" + cBVCode.Trim() + "'");
                                if (existEntity != null && existEntity.Count > 0)
                                {
                                    txtResult.Text += "发票编号【" + cBVCode + "】已被调整为代开票,导入被忽略(出错行：" + (index + 2).ToString() + ")\r\n";
                                    continue;
                                }

                                entity.UFAccountNo = UFAccountNo;
                                entity.BillUnit = Billcompany;
                                entity.BudgetUnit = Billcompany;
                                entity.dDate = System.Convert.ToDateTime(dDate);
                                entity.cBVCode = cBVCode.Trim();
                                entity.cCusCode = cCusCode;
                                entity.cMemo = cMemo;
                                entity.cCategoryCode = cCategoryCode;
                                entity.cInvCode = cInvCode;
                                entity.billYear = System.Convert.ToDateTime(dDate).Year;
                                entity.billMonth = System.Convert.ToDateTime(dDate).Month;
                                entity.invCategoryCode = cCategoryCode;
                                if(DataValid.IsNumeric(Quantity))
                                {
                                    entity.iQuantity = System.Convert.ToDecimal(Quantity);
                                }

                                if (DataValid.IsNumeric(Unit))
                                {
                                    entity.iTaxUnitPrice = System.Convert.ToDecimal(Unit);
                                }

                                if (DataValid.IsNumeric(Price))
                                {
                                    entity.iNatMoney = System.Convert.ToDecimal(Price);
                                }
                                if (DataValid.IsNumeric(NatSum))
                                {
                                    entity.iNatSum = System.Convert.ToDecimal(NatSum);

                                }
                                entity.SourceType = System.Convert.ToInt16("2");
                                entity.CreatedOn = DateTime.Now;
                                entity.CreatedBy = CurrentUserID;
                                entity.Deleted = false;
                                
                                
                                bll.Insert(entity);
                                
                            }
                            catch (Exception ex)
                            {
                                txtResult.Text += ",导入失败(出错行：" + (index + 2).ToString() + ")，错误提示："+ex.Message+"\r\n";
                                ClientScript.RegisterStartupScript(this.GetType(), "saveandssscloseerror", "alert('" + ex.Message + ",导入中断(出错行：" + (index + 2).ToString() + ")')", true);

                            }
                            finally
                            {
                                trans.Complete();
                                sucNum++;
                                
                            }
                        }
                    }
                    new BudgetBll().UpdateBillInstrument();
                    txtResult.Text += "\r\n"+"数据导入完成。共成功导入" + Convert.ToSingle(sucNum)+"条数据。";
                    ClientScript.RegisterStartupScript(this.GetType(), "saveandssscloseerror", "alert('导入完成!');", true);
                }
                catch(Exception ex) {
                    txtResult.Text += ",导入失败，错误提示：" + ex.Message + "\r\n";
                    ClientScript.RegisterStartupScript(this.GetType(), "saveandssscloseerror", "alert('" + ex.Message + "');", true);
                    return;
                }
            }
        }

        protected void btnUFImport_Click(object sender, EventArgs e)
        {
            BudgetBll bll = new BudgetBll();
            string company, sYear, sMonth;
            company = ddlCompany.SelectedValue.ToString();
            sYear = ddlBudgetYear.SelectedValue.ToString();
            sMonth = ddlBudgetMonth.SelectedValue.ToString();

            if (company == "")
            {
                ClientScript.RegisterStartupScript(this.GetType(), "saveandssscloseerror", "alert('请选择开票公司!');", true);
                msg.Text = "请选择开票公司。";
                return;
            }
            if (bll.BillDataStatus(sYear, sMonth, company) == 1)
            {
                ClientScript.RegisterStartupScript(this.GetType(), "saveandssscloseerror", "alert('选择月份的销售数据（导入）已关账');", true);
                msg.Text = "选择月份的销售数据（导入）已关账";
                return;
            }
            if (bll.AccountCloseStatus(sYear, sMonth, company) == 1)
            {
                ClientScript.RegisterStartupScript(this.GetType(), "saveandssscloseerror", "alert('选择月份的销售数据已关账!');", true);
                msg.Text = "选择月份的销售数据已关账";
                return;
            }
            if (bll.PreBillDataStatus(sYear, sMonth, company) > 0)
            {
                ClientScript.RegisterStartupScript(this.GetType(), "saveandssscloseerror", "alert('当前月份之前的销售数据导入未完成，无法导入当前月份数据!');", true);
                msg.Text = "当前月份之前的销售数据导入未完成，无法导入当前月份数据";
                return;
            }

            //ClientScript.RegisterStartupScript(this.GetType(), "saveandssscloseerror", "document.getElementById('txtResult').value='正在导入数据．．．';", true);
            txtResult.Text = "正在导入数据．．．";
                

            string budgetYearmonth = "";

            budgetYearmonth = ddlBudgetYear.SelectedValue.ToString() + "-" + ddlBudgetMonth.SelectedValue.ToString() + "-01";
            bll.syncUFBills(budgetYearmonth, ddlCompany.SelectedValue);


            //ClientScript.RegisterStartupScript(this.GetType(), "saveandssscloseerror", "unshowprocessbar();", true);
            ClientScript.RegisterStartupScript(this.GetType(), "saveandssscloseerror", "<script lanuage=javascript>document.getElementById('txtResult').value='数据导入已完成。';</script>", true);
            txtResult.Text = "数据导入完成。";
        }

        protected void ddlCompany_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ddlCompany.SelectedValue.Contains("润达") || ddlCompany.SelectedValue.Contains("康祥"))
            {
                btnUFImport.Enabled =true;
                btnExcel.Enabled = false;
            }else
            {
                btnUFImport.Enabled = false;
                btnExcel.Enabled = true;
            }
            if (ddlCompany.SelectedValue != "")
            {
                BudgetBll bll = new BudgetBll();
                string UnlockYearmonth = bll.GetunLockMonth(ddlCompany.SelectedValue);
                ddlBudgetMonth.SelectedValue = UnlockYearmonth.Substring(5, 2);
            }

        }
    }
}


